import { unified } from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeRaw from 'rehype-raw'
import rehypeStringify from 'rehype-stringify'
import rehypeHighlight from 'rehype-highlight'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css'

// 注册Vue语言支持
import vue from 'highlight.js/lib/languages/xml'
hljs.registerLanguage('vue', vue)

/**
 * 处理文章内容，确保代码块正确高亮显示
 * @param content 文章HTML内容
 */
export async function processContent(content: string): Promise<string> {
  // 处理代码块，将其包装在pre和code标签中
  const processedContent = content.replace(
    /<pre><code class="language-(.*?)">(([\s\S])*?)<\/code><\/pre>/g,
    (match, language, code) => {
      // 对代码进行HTML实体编码，防止被浏览器解析为HTML
      const escapedCode = code
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;')
      
      return `<div class="code-block"><pre><code class="language-${language}">${escapedCode}</code></pre></div>`
    }
  )

  // 使用unified处理内容
  const result = await unified()
    .use(remarkParse)
    .use(remarkRehype, { allowDangerousHtml: true })
    .use(rehypeRaw)
    .use(rehypeHighlight, true )
    .use(rehypeStringify)
    .process(processedContent)

  return String(result)
}